import Ember from 'ember';
import csrfGetter from './csrf-getter';

function docreate(action, treeId, nodeId, name, body) {
  return {
    action: action,
    treeId: treeId,
    nodeId: nodeId,
    name: name,
    body: body
  };
}

// {"nodeId":304,"treeId":0,"action":"ADD","name":"achild","body":null,"generatedNodeId":305,"actionResult":"SUCCESS"}

export default Ember.Object.create({
  deleteAction(treeId, nodeId, name, body) {
      return docreate("DELETE", treeId, nodeId, name, body);
    },
    editAction(treeId, nodeId, name, body) {
      return docreate("EDIT", treeId, nodeId, name, body);
    },
    createAction(treeId, nodeId, name, body) {
      return docreate("ADD", treeId, nodeId, name, body);
    },
    isSuccess(tua) {
      if (tua.actionResult === "SUCCESS") {
        return true;
      } else {
        return false;
      }
    },
    getGeneratedNodeId(tua) {
      if (this.isSuccess(tua)) {
        return tua.generatedNodeId;
      } else {
        return -1;
      }
    },
    ajax(treeModel, data) {
      var t = Ember.typeOf(treeModel),
        tid;

      if (t === 'string' || t === 'number') {
        tid = treeModel;
      } else {
        tid = treeModel.get('id');
      }
      return Ember.$.ajax({
        method: 'PUT',
        url: "/treenodes/" + tid + '/update',
        data: JSON.stringify(data),
        headers: csrfGetter(),
        dataType: 'json',
        contentType: 'application/json; charset=UTF-8',
      });
    }
});
